{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "from scipy.fftpack import fft,ifft\n",
    "import matplotlib.pyplot as plt\n",
    "from matplotlib.pylab import mpl\n",
    "%matplotlib inline\n",
    "\n",
    "mpl.rcParams['font.sans-serif'] = ['SimHei']   #显示中文\n",
    "mpl.rcParams['axes.unicode_minus']=False       #显示负号\n",
    "\n",
    "# 设置图片尺寸 14\" x 7\"\n",
    "# rc: resource configuration\n",
    "plt.rc('figure', figsize = (14, 7))\n",
    "# 设置字体 14\n",
    "plt.rc('font', size = 14)\n",
    "# 不显示顶部和右侧的坐标线\n",
    "plt.rc('axes.spines', top = False, right = False)\n",
    "# 不显示网格\n",
    "plt.rc('axes', grid = False)\n",
    "# 设置背景颜色是白色\n",
    "plt.rc('axes', facecolor = 'white')\n",
    "from pandas import Series\n",
    "import math\n",
    "import os\n",
    "\n",
    "from sklearn import svm\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.decomposition import PCA"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "def  psfeatureTime(data,p1,p2):\n",
    "#     #均值\n",
    "    df_mean=data[p1:p2].mean()\n",
    "# #     #方差\n",
    "    df_var=data[p1:p2].var()\n",
    "#     #标准差\n",
    "    df_std=data[p1:p2].std()\n",
    "#     #均方根\n",
    "    df_rms=math.sqrt(pow(df_mean,2) + pow(df_std,2))\n",
    "#     #偏度\n",
    "    df_skew=data[p1:p2].skew()\n",
    "#     峭度\n",
    "    df_kurt=data[p1:p2].kurt()\n",
    "    sum=0\n",
    "    for i in range(p1,p2):\n",
    "        sum+=math.sqrt(abs(data[i]))\n",
    "    #波形因子\n",
    "    df_boxing=df_rms / (abs(data[p1:p2]).mean())\n",
    "    #峰值因子\n",
    "    df_fengzhi=(max(data[p1:p2])) / df_rms\n",
    "    #脉冲因子\n",
    "    df_maichong=(max(data[p1:p2])) / (abs(data[p1:p2]).mean())\n",
    "    #裕度因子\n",
    "    df_yudu=(max(data[p1:p2])) / pow((sum/(p2-p1)),2)\n",
    "#     featuretime_list = [df_rms,df_skew,df_kurt,df_boxing,df_fengzhi,df_maichong,df_yudu]\n",
    "#     featuretime_list = [df_kurt,df_boxing,df_fengzhi,df_maichong,df_yudu]\n",
    "    return df_mean,df_var,df_std,df_rms,df_skew,df_kurt,df_boxing,df_fengzhi,df_maichong,df_yudu"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "def data2fft(data):\n",
    "    N = 4000\n",
    "    fft_y = np.abs(fft(data))  # 数据转为fft\n",
    "    fft_y =fft_y[0:N]       #  取fft中的前N个频率值\n",
    "    fft_frequency = np.arange(N)  # 构造频率数据\n",
    "    \n",
    "    # 构造最大频率\n",
    "    fft_y_reduce50 =fft_y[50:].tolist() # 抛弃频率的前50行数据\n",
    "    fft_y_max = max(fft_y_reduce50)  # 找出原频率数据中最大的幅值\n",
    "    fft_frequency_mean=np.mean(fft_y_reduce50)\n",
    "    fft_frequency_var=np.var(fft_y_reduce50)\n",
    "    fft_frequency_max = fft_y_reduce50.index(max(fft_y_reduce50)) + 50  # 找出原频率数据中幅值最大对应的频率值\n",
    "    \n",
    "    # 构造基频-----------------------------------------------------------新增加的特征\n",
    "    fft_y_base =fft_y[50:200].tolist() # 选择频率的前50-200行数据\n",
    "    fft_y_base_max = max(fft_y_base)  # 找出原频率数据中前50-200行最大的幅值\n",
    "    fft_frequency_base_max = fft_y_base.index(max(fft_y_base)) + 50  # 找出频率数据中幅值最大对应的频率值\n",
    "    \n",
    "    # 构造基频的2倍频-----------------------------------------------------新增加的特征\n",
    "    fft_y_base2 =fft_y[300:350].tolist() # 选择频率的前300-350行数据\n",
    "    fft_y_base2_max = max(fft_y_base2)  # 找出原频率数据中前300-350行最大的幅值\n",
    "    fft_frequency_base2_max = fft_y_base2.index(max(fft_y_base2)) + 300  # 找出频率数据中幅值最大对应的频率值\n",
    "    \n",
    "    # 构造基频的3倍频-----------------------------------------------------新增加的特征\n",
    "    fft_y_base3 =fft_y[400:500].tolist() # 选择频率的前300-350行数据\n",
    "    fft_y_base3_max = max(fft_y_base3)  # 找出原频率数据中前300-350行最大的幅值\n",
    "    fft_frequency_base3_max = fft_y_base3.index(max(fft_y_base3)) + 400  # 找出频率数据中幅值最大对应的频率值\n",
    "    \n",
    "    # 构造200频率-----------------------------------------------------新增加的特征\n",
    "    fft_y_base200 =fft_y[200:300].tolist() # 选择频率的前200-300行数据\n",
    "    fft_y_base200_max = max(fft_y_base200)  # 找出原频率数据中前200-300行最大的幅值\n",
    "    fft_frequency_base200_max = fft_y_base200.index(max(fft_y_base200)) + 200  # 找出频率数据中幅值最大对应的频率\n",
    "    \n",
    "    # 构建低频是否存在异常频率-----------------------------------------------------新增加的特征\n",
    "    fft_frequency_low_other = 0\n",
    "    if fft_y_base_max < fft_y_base200_max:\n",
    "        fft_frequency_low_other = 1\n",
    "    \n",
    "    # 构造倍频的比值-----------------------------------------------------新增加的特征\n",
    "    ratio_base = 0\n",
    "    ratio_base2 = 0\n",
    "    ratio_base3 = 0\n",
    "    a = abs((fft_frequency_max / fft_frequency_base_max) - round(fft_frequency_max / fft_frequency_base_max))\n",
    "    b = abs((fft_frequency_base2_max / fft_frequency_base_max) - round(fft_frequency_base2_max / fft_frequency_base_max))\n",
    "    c = abs((fft_frequency_base3_max / fft_frequency_base_max) - round(fft_frequency_base3_max / fft_frequency_base_max))\n",
    "    if a > 0.06:\n",
    "        ratio_base = 1\n",
    "    if b > 0.06:\n",
    "        ratio_base2 = 1\n",
    "    if c > 0.06:\n",
    "        ratio_base3 = 1\n",
    "        \n",
    "    \n",
    "    return fft_frequency_mean,fft_frequency_var,fft_y_max, fft_frequency_max, fft_y_base_max, fft_frequency_base_max, fft_y_base2_max, fft_frequency_base2_max, fft_y_base3_max, fft_frequency_base3_max, fft_y_base200_max, fft_frequency_base200_max, fft_frequency_low_other, ratio_base, ratio_base2, ratio_base3\n",
    "       "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "def oneFftData(train_data_fft):\n",
    "    data_fft = {}\n",
    "    columns = [\"F_ai1\",\"F_ai2\",\"B_ai1\",\"B_ai2\"]\n",
    "    for i in columns:\n",
    "        df_mean,df_var,df_std,df_rms,df_skew,df_kurt,df_boxing,df_fengzhi,df_maichong,df_yudu=psfeatureTime(train_data_fft[i],0,10000)\n",
    "        data_fft[i + \"_time_mean\"] = df_mean\n",
    "        data_fft[i + \"_time_var\"] = df_var\n",
    "        data_fft[i + \"_time_std\"] = df_std\n",
    "        \n",
    "        data_fft[i + \"_time_rms\"] = df_rms\n",
    "        data_fft[i + \"_time_skew\"] = df_skew\n",
    "        data_fft[i + \"_time_kurt\"] = df_kurt\n",
    "        data_fft[i + \"_time_boxing\"] = df_boxing\n",
    "        data_fft[i + \"_time_fengzhi\"] = df_fengzhi\n",
    "        data_fft[i + \"_time_maichong\"] = df_maichong\n",
    "        data_fft[i + \"_time_yudu\"] = df_yudu\n",
    " \n",
    "    for i in columns:\n",
    "        Fs = 51200    # 采样频率\n",
    "        flag1 = 1000  # 数据起始位置\n",
    "        flag2 = 1000 + Fs   # 数据结束位置\n",
    "        train_data_fft = train_data_fft[flag1:flag2]  \n",
    "        \n",
    "        fft_frequency_mean,fft_frequency_var,fft_y_max, fft_frequency_max, fft_y_base_max, fft_frequency_base_max, fft_y_base2_max, fft_frequency_base2_max, fft_y_base3_max, fft_frequency_base3_max, fft_y_base200_max, fft_frequency_base200_max, fft_frequency_low_other, ratio_base, ratio_base2, ratio_base3 = data2fft(train_data_fft[i])\n",
    "        data_fft[i + \"_fft_y_max\"] = fft_y_max\n",
    "        data_fft[i + \"_fft_frequency_max\"] = fft_frequency_max\n",
    "        data_fft[i + \"_fft_frequency_mean\"] = fft_frequency_mean\n",
    "        data_fft[i + \"_fft_frequency_var\"] = fft_frequency_var\n",
    "\n",
    "        data_fft[i + \"_fft_y_base_max\"] = fft_y_base_max                        #--------------新增加的特征\n",
    "        data_fft[i + \"_fft_frequency_base_max\"] = fft_frequency_base_max        #--------------新增加的特征\n",
    "        data_fft[i + \"_fft_y_base2_max\"] = fft_y_base2_max                      #--------------新增加的特征\n",
    "        data_fft[i + \"_fft_frequency_base2_max\"] = fft_frequency_base2_max      #--------------新增加的特征\n",
    "        data_fft[i + \"_fft_y_base3_max\"] = fft_y_base3_max                      #--------------新增加的特征\n",
    "        data_fft[i + \"_fft_frequency_base3_max\"] = fft_frequency_base3_max      #--------------新增加的特征\n",
    "        data_fft[i + \"_fft_y_base200_max\"] = fft_y_base200_max                  #--------------新增加的特征\n",
    "        data_fft[i + \"_fft_frequency_base200_max\"] = fft_frequency_base200_max  #--------------新增加的特征\n",
    "        data_fft[i + \"_fft_frequency_low_other\"] = fft_frequency_low_other      #--------------新增加的特征\n",
    "        data_fft[i + \"_ratio_base\"] = ratio_base                                #--------------新增加的特征\n",
    "        data_fft[i + \"_ratio_base2\"] = ratio_base2                              #--------------新增加的特征\n",
    "        data_fft[i + \"_ratio_base3\"] = ratio_base3   \n",
    "    \n",
    "    data_fft[\"ai1_frequency_max_diff\"] = data_fft[\"F_ai1_fft_frequency_max\"] - data_fft[\"B_ai1_fft_frequency_max\"]\n",
    "    data_fft[\"ai1_frequency_max_mean\"] = (data_fft[\"F_ai1_fft_frequency_max\"] + data_fft[\"B_ai1_fft_frequency_max\"])/2\n",
    "    data_fft[\"ai2_frequency_max_diff\"] = data_fft[\"F_ai2_fft_frequency_max\"] - data_fft[\"B_ai2_fft_frequency_max\"]\n",
    "    data_fft[\"ai2_frequency_max_mean\"] = (data_fft[\"F_ai2_fft_frequency_max\"] + data_fft[\"B_ai2_fft_frequency_max\"])/2\n",
    "    data_fft[\"F_frequency_max_diff\"] = data_fft[\"F_ai1_fft_frequency_max\"] - data_fft[\"F_ai2_fft_frequency_max\"]\n",
    "    data_fft[\"F_frequency_max_mean\"] = (data_fft[\"F_ai1_fft_frequency_max\"] + data_fft[\"F_ai2_fft_frequency_max\"])/2\n",
    "    data_fft[\"B_frequency_max_diff\"] = data_fft[\"B_ai1_fft_frequency_max\"] - data_fft[\"B_ai2_fft_frequency_max\"]\n",
    "    data_fft[\"B_frequency_max_mean\"] = (data_fft[\"B_ai1_fft_frequency_max\"] + data_fft[\"B_ai2_fft_frequency_max\"])/2\n",
    "\n",
    "# 统计单个样本频率比值异常的数目--------------新增加的特征\n",
    "    columns2 = [\"B_ai2_ratio_base\",\"B_ai2_ratio_base2\",\"B_ai2_ratio_base3\",\"F_ai2_ratio_base\",\"F_ai2_ratio_base2\",\"F_ai2_ratio_base3\"]\n",
    "    sum_half = 0\n",
    "    for j in columns2:\n",
    "        if data_fft[j] == 1:\n",
    "            sum_half += 1\n",
    "    data_fft[\"ratio_half\"] = sum_half\n",
    "    \n",
    "# 统计单个样本频率比值异常的数目--------------新增加的特征\n",
    "    columns3 = [\"B_ai2_ratio_base\",\"B_ai2_ratio_base2\",\"B_ai2_ratio_base3\",\"F_ai2_ratio_base\",\"F_ai2_ratio_base2\",\"F_ai2_ratio_base3\",\n",
    "               \"B_ai1_ratio_base\",\"B_ai1_ratio_base2\",\"B_ai1_ratio_base3\",\"F_ai1_ratio_base\",\"F_ai1_ratio_base2\",\"F_ai1_ratio_base3\"]\n",
    "    sum_all = 0\n",
    "    for k in columns3:\n",
    "        if data_fft[k] == 1:\n",
    "            sum_all += 1\n",
    "    data_fft[\"ratio_all\"] = sum_all\n",
    "    return data_fft\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "def fftDataFrame(dataPath):\n",
    "    allFileNameList=[]\n",
    "    for root, dirs, files in os.walk(dataPath):  \n",
    "        allFileNameList=files\n",
    "    fileNameList=[]\n",
    "    fileId=[]\n",
    "    for i in allFileNameList:\n",
    "        if  i[-5:-4]==\"F\":\n",
    "            fileNameList.append(i)\n",
    "            fileId.append(i[0:-6])\n",
    "                 \n",
    "    datalist=[]\n",
    "    \n",
    "    fileId=fileId[375:500]\n",
    "    \n",
    "    for name in fileId:\n",
    "        data_F=pd.read_csv(dataPath+name+\"_F.csv\")\n",
    "        data_B=pd.read_csv(dataPath+name+\"_B.csv\")\n",
    "        train_data = pd.DataFrame()\n",
    "        train_data[\"F_ai1\"]=data_F[\"ai1\"]\n",
    "        train_data[\"F_ai2\"]=data_F[\"ai2\"]\n",
    "        train_data[\"B_ai1\"]=data_B[\"ai1\"]\n",
    "        train_data[\"B_ai2\"]=data_B[\"ai2\"]\n",
    "        train_data\n",
    "        fftData=pd.DataFrame(oneFftData(train_data),index=[name])\n",
    "        datalist.append(fftData)\n",
    "    allFftData=pd.concat(datalist,axis=0)\n",
    "    return allFftData"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "# ppath=os.getcwd() +\"\\\\Motor_tain\\\\Positive\\\\\"\n",
    "# npath=os.getcwd() +\"\\\\Motor_tain\\\\Negative\\\\\"\n",
    "# tpath=os.getcwd() +\"\\\\Motor_testP\\\\\"\n",
    "npath=\"./Motor_testP/\"\n",
    "# ppath=\"./Motor_tain/Positive/\"\n",
    "# tpath=\"./Motor_testP/\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "# fftDataP=fftDataFrame(ppath)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "# fftDataP.to_csv(\"PositiveData.csv\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "fftDataN=fftDataFrame(npath)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "fftDataN.to_csv(\"TEST-p4.csv\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "# fftDataT=fftDataFrame(tpath)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "# fftDataT.to_csv(\"testData.csv\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "# trainfftData=pd.concat([fftDataP,fftDataN],axis=0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "# fftDataT.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
